> Just wondering if it is also bad to use the following:
Yes
> Our teacher asked us how to switch two variables without using any others
Wonder if you will learn anything useful, as opposed to a bunch of silly tricks
Swapping variables without temporaries ceased to be of any use when we left assembler and started using C.
Code:
#include <stdio.h>
void s1 ( int a, int b ) {
a ^= b;
b ^= a;
a ^= b;
printf( "%d %d\n", a, b );
}
void s2 ( int a, int b ) {
int temp = a;
a = b;
b = temp;
printf( "%d %d\n", a, b );
}
int main ( ) {
s1( 1, 2 );
s2( 1, 2 );
return 0;
}
Guess which one is more efficient when you compile this?
gcc -S prog.c
Guess which one is more efficient when you turn on the optimiser?
gcc -S -O prog.c
In both cases, the results are in prog.s
User's of GUI front end compilers will have to RTM to find out.
Guess which one is clearer in it's intent to the average reader?
Guess which one will work with types other than int?
> Is this really much worse (if any),
You might be relying on unspecified overflow and underflow properties of integers